package com.explorati.LeetCode350.insertionoftwoarrays2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 350. Intersection of Two Arrays II
 * 
 * Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
 * 
 * @author explorati
 *
 */
public class Solution {
	public static int[] intersect(int[] nums1, int[] nums2) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums1.length; i++) {
			if (!map.containsKey(nums1[i])) {
				map.put(nums1[i], 1);
			} else {
				map.put(nums1[i], map.get(nums1[i]) + 1);
			}
		}

		ArrayList<Integer> list = new ArrayList<>();
		for (int i : nums2) {
			if (map.containsKey(i)) {
				list.add(i);
				map.put(i, map.get(i) - 1);
				if (map.get(i) == 0) {
					map.remove(i);
				}
			}
		}

		int[] res = new int[list.size()];
		for (int i = 0; i < res.length; i++) {
			res[i] = list.get(i);
		}
		return res;
	}

	public static void main(String[] args) {
		int[] arr1 = { 4, 9, 5 };
		int[] arr2 = { 9, 4, 9, 8, 4 };

		int[] res = intersect(arr1, arr2);
		for (int i : res) {
			System.out.print(i + "  ");
		}
	}
}
